// 初始数据
const initState = {
  allList: [] as ChannelType[],
  currentId: 0,
  // 新建userList属性，设置初始值，表示用户自己的频道列表
  userList: [] as ChannelType[],
};

// 频道数据格式
export type ChannelType = {
  id: number;
  name: string;
};

// 频道 Action 格式
export type ChannelAction =
  | { type: 'channel/saveList'; payload: ChannelType[] }
  | { type: 'channel/saveUserList'; payload: ChannelType[] }
  // 1. 扩展ActionType的类型， payload接收id
  | { type: 'channel/delUserChannelById'; payload: number }
  | { type: 'channel/addUserChannel'; payload: ChannelType }
  | { type: 'channel/setChannelId'; payload: number };

// 频道 reducer 纯函数
export default function channelReducer(
  state = initState,
  action: ChannelAction
) {
  switch (action.type) {
    // 保存频道列表
    case 'channel/saveList':
      return {
        ...state,
        allList: [...action.payload],
      };
    case 'channel/saveUserList':
      return {
        ...state,
        userList: [...action.payload],
      };
    // 计算逻辑的放reducer
    case 'channel/delUserChannelById':
      return {
        ...state,
        userList: state.userList.filter((item) => item.id !== action.payload),
      };
    case 'channel/addUserChannel':
      return {
        ...state,
        userList: [...state.userList, action.payload],
      };
    case 'channel/setChannelId':
      return {
        ...state,
        currentId: action.payload,
      };
    default:
      return state;
  }
}
